package com.handinglian.employee.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.handinglian.common.utils.FastJsonUtil;
import com.handinglian.common.utils.GeneralUtil;
import com.handinglian.employee.dto.ExtensionDto;
import com.handinglian.employee.entity.Extension;
import com.handinglian.employee.mapper.ExtensionMapper;
import com.handinglian.employee.service.ExtensionService;
import com.handinglian.thirdparty.YunyiApiService;
import com.handinglian.thirdparty.dto.YyExtensionMessageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("extensionService")
public class ExtensionServiceImpl implements ExtensionService {
    @Autowired
    private ExtensionMapper extensionMapper;
    @Autowired
    private YunyiApiService yunyiApiService;

    @Override
    @Transactional
    @Async
    public void refreshExtension()  {
        List<Extension> extensions = extensionMapper.find();
        //获取数据库中的分机号
        List<String> dbExtensionNos = extensions.stream().map(extension -> extension.getExtenNo()).collect(Collectors.toList());

        List<YyExtensionMessageDto> yyExtensionMessageDtos  = null;
        try {
            yyExtensionMessageDtos = yunyiApiService.getExtension(null);
        } catch (Exception e) {
            log.error("获取云翌分机信息异常！！");
            return;
        }
        //获取云翌平台的分机号
        List<String> yyExtensionNos = yyExtensionMessageDtos.stream().map(yyExtensionMessageDto -> yyExtensionMessageDto.getExten()).collect(Collectors.toList());


        //插入分机
        List<String> addExtensionNos = GeneralUtil.getAddList(yyExtensionNos, dbExtensionNos);
        List<YyExtensionMessageDto> addList = yyExtensionMessageDtos.stream().filter(yyExtensionMessageDto -> addExtensionNos.contains(yyExtensionMessageDto.getExten())).collect(Collectors.toList());
        List<Extension> extensionList = new ArrayList<>();
        addList.forEach(yyExtensionMessageDto -> {
            extensionList.add(castYyExtensionMessageDtoToExtension(yyExtensionMessageDto));
        });
        if (CollectionUtil.isNotEmpty(extensionList)){
            extensionMapper.batchInsert(extensionList);
        }

        //删除分机
        List<String> missingExtensionNos = GeneralUtil.getMissingList(yyExtensionNos, dbExtensionNos);
        if (missingExtensionNos.size() > 0){
            extensionMapper.deleteByExtenNoIn(missingExtensionNos);
        }

        //更新分机
        dbExtensionNos.removeAll(missingExtensionNos);
        List<Extension> updateList = extensions.stream().filter(extension -> dbExtensionNos.contains(extension.getExtenNo())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(updateList)){
            extensionMapper.updateBatch(updateList);
        }
    }

    private Extension castYyExtensionMessageDtoToExtension(YyExtensionMessageDto yyExtensionMessageDto){
        Extension extension = new Extension();
        extension.setDeptName(yyExtensionMessageDto.getDeptName());
        extension.setDisplayName(yyExtensionMessageDto.getDisplayName());
        extension.setExtenNo(yyExtensionMessageDto.getExten());
        extension.setExtenPassword(yyExtensionMessageDto.getExtenPassword());
        extension.setMobile(yyExtensionMessageDto.getMobile());
        Integer needRecord = StrUtil.isBlank(yyExtensionMessageDto.getNeedRecord())?0:Integer.valueOf(yyExtensionMessageDto.getNeedRecord());
        extension.setNeedRecord(needRecord);
        extension.setRegisterIp(yyExtensionMessageDto.getRegisterip());
        extension.setStatus(Integer.valueOf(yyExtensionMessageDto.getStatus()));
        extension.setTransferAll(yyExtensionMessageDto.getTransferall());
        extension.setTransferBusy(yyExtensionMessageDto.getTransferbusy());
        extension.setTransferNoAnswer(yyExtensionMessageDto.getTransfernoanswer());
        extension.setTransferOffline(yyExtensionMessageDto.getTransferoffline());
        extension.setUserName(yyExtensionMessageDto.getUserName());
        extension.setPassword(yyExtensionMessageDto.getPassWord());
        extension.setCreateTime(new Date());
        return extension;
    }

    @Override
    public Extension loadExtensionByUserIdIsNull() {
        return extensionMapper.findFirstByUserIdIsNull();
    }

    @Override
    @Transactional
    public int updateExtension(Extension extension) {
        return extensionMapper.updateByPrimaryKeySelective(extension);
    }

    @Override
    @Transactional
    public int updateExtensionByUserId(Integer updatedUserId, Integer userId) {
        return extensionMapper.updateUserIdByUserId(updatedUserId, userId);
    }

    @Override
    public Integer countByExtensionUserIdIsNull() {
        return extensionMapper.countByUserIdIsNull();
    }

    @Override
    public ExtensionDto loadExtensionByUserId(Integer userId) {
        Extension extension = extensionMapper.findOneByUserId(userId);
        return FastJsonUtil.ObjectToObject(extension, ExtensionDto.class);
    }

    @Override
    public List<Extension> inquireUserIdByExtenNo(Collection<String> extenNoCollection) {
        return extensionMapper.findByExtenNoIn(extenNoCollection);
    }

    @Override
    @Transactional
    public int updateUserIdByUserIdIsNull(Integer updatedUserId) {
        return extensionMapper.updateUserIdByUserIdIsNull(updatedUserId);
    }
}
